package com.gitee.farmer.im.controller;

import com.gitee.farmer.im.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

import com.gitee.farmer.im.service.UserService;

/**
 * @author tech-farmer
 * @ClassName: TestController
 * @Description: (这里用一句话描述这个类的作用)
 * @date 2022/2/25 10:23
 */
@Controller
@RequestMapping("/test")
public class TestController {

    @Value("${file.upload.path:/tmp/}")
    private String uploadFilePath;

    @Value("${tencent.map.key}")
    private String mapKey;

    private final UserService userService;

    public TestController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/index")
    public String index(String userName, ModelMap map){
        map.put("userName",userName);
        map.put("key",mapKey);
        return "test";
    }

    @RequestMapping("/mapApi")
    @ResponseBody
    public Object  mapApi(String api, String method, String keyword , String boundary, HttpServletResponse response) throws Exception {
        String url = "https://apis.map.qq.com/ws" + api +"?" +keyword +"&key="+mapKey+"&page_size=5&page_index=1";
        final URL httpUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
        connection.setRequestMethod(method);
        connection.setDoInput(true);
        connection.connect();
        InputStream inputStream = connection.getInputStream();
        StringBuilder sb = new StringBuilder();
        String str;
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        while ((str = reader.readLine())!= null) {
            sb.append(str).append("\r\n");
        }
        return sb.toString();
    }

    @RequestMapping("/mapSnapshot")
    @ResponseBody
    public Object  mapApi(String url) throws Exception {
        return HttpUtils.uploadFile(url + "&key=" + mapKey,"png");
    }

    @RequestMapping("uploadFile")
    @ResponseBody
    public Object uploadFile(MultipartFile file){
        final String yyyyMMdd = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String fileName = UUID.randomUUID().toString().replace("-","")  + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
        File dir = new File(uploadFilePath + yyyyMMdd);
        if(!dir.exists()){
            dir.mkdirs();
        }
        File localFile = new File(uploadFilePath + yyyyMMdd + "/" + fileName);
        try(final InputStream inputStream = file.getInputStream(); final FileOutputStream fileOutputStream = new FileOutputStream(localFile)){
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf))!= -1){
                fileOutputStream.write(buf,0,len);
            }
            fileOutputStream.flush();
        }catch (Exception e){

        }
        return "/" + yyyyMMdd + "/" + fileName;
    }


    @RequestMapping("/contacts")
    @ResponseBody
    public Object contacts(){
        return userService.findAll();
    }

}
